package com.yuchen.ishop.web.app;

import com.yuchen.core.MyPager;
import com.yuchen.core.cache.J2CacheUtils;
import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.entity.Dictionary;
import com.yuchen.ishop.service.CacheService;
import com.yuchen.ishop.service.goods.GoodsImgRestClient;
import com.yuchen.ishop.service.goods.GoodsRestClient;
import com.yuchen.ishop.vo.CookieUserInfo;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.ishop.web.mytags.MyEL;
import com.yuchen.utils.CookieUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页,一些跳转
 */
@Controller
public class HomeAction extends BaseAction {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private GoodsRestClient goodsRestClient;

    @Autowired
    private GoodsImgRestClient goodsImgRestClient;

    @RequestMapping(value = {"index"})
    public String index(ModelMap modelMap, HttpServletRequest request) {
        List<Dictionary> dictionaries = cacheService.getDictionaryCache();
        if (dictionaries != null && dictionaries.size() > 0) {
            Map params = new HashMap(2);
            params.put("pageSize",6);
            for(Dictionary dictionary : dictionaries){
                params.put("dictionaryId",dictionary.getId());
                MyPager myPager = goodsRestClient.findByLimit(params);
                if(myPager!=null)
                   dictionary.setGoodses(myPager.getRecords());
            }
        }
        modelMap.addAttribute("sysGoodsType", cacheService.getDictionaryCache());

        //推荐商品
        Map params = new HashMap(2);
        params.put("pageSize",8);
        params.put("recommend",1);
        MyPager myPager = goodsRestClient.findByLimit(params);
        if(myPager!=null)
            modelMap.addAttribute("recommendGoods", myPager.getRecords());
        modelMap.addAttribute("myNav","index");
        return "index";
    }

    @RequestMapping(value = {"logout"})
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        String cookieVal = null;
        try {
            cookieVal = CookieUtils.findCookie(Gobals.COOKIE_ID, request);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(cookieVal)) {
            Map map = MyEL.decodeIshopid(cookieVal);
            J2CacheUtils.evict(Gobals.CACHE_USERINFO, map.get("role") + "_" + map.get("id"));
        }
        CookieUtils.deleteCookie(Gobals.COOKIE_ID, response);
        return "redirect:/";
    }

    @RequestMapping(value = {"error"})
    public String error(String type,RedirectAttributes redirectAttributes) {
        if("order".equals(type)){
            redirectAttributes.addFlashAttribute(Gobals.MSG,errorJson("卖家无法购买商品！"));
        }
        return "error";
    }

    @RequestMapping(value = {"my"})
    public String my(HttpServletRequest request, HttpServletResponse response) {
        CookieUserInfo userInfo = BaseAction.cookie2UserInfo(request);
        if (userInfo == null || !userInfo.isState()) {
            return "redirect:/goLogin.htm";
        }
        String role = userInfo.getRole();
        if ("seller".equals(role) || "xiaoer".equals(role)) {
            return "redirect:/my/seller/index.htm";
        }
        if ("buyer".equals(role)) {
            return "redirect:/my/buyer/index.htm";
        }
        return "error";
    }

    @RequestMapping(value = {"/goRegister"}, method = RequestMethod.GET)
    public String toRegister() {
        return "register1123";
    }

    @RequestMapping(value = "/goLogin")
    public String goLogin() {
        return "login";
    }

    //添加到购物车
    @RequestMapping(value = {"/cartCookieAjax"}, method = RequestMethod.POST)
    @ResponseBody
    public Map cartCookieAjax(Long goodsId,HttpServletRequest request, HttpServletResponse response) {
        if(goodsId == null) return errorJson();
        try {
            String cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID,request);
            if(StringUtils.isNotBlank(cart)){
                String[] goodsIds = StringUtils.split(cart,",");
                if(!ArrayUtils.contains(goodsIds,goodsId.toString())){
                    StringBuilder cartSb = new StringBuilder();
                    cartSb.append(cart).append(",").append(goodsId);
                    CookieUtils.addCookie(Gobals.COOKIE_CART_ID,cartSb.toString(),CookieUtils.one_day,response);
                }
            }else{
                CookieUtils.addCookie(Gobals.COOKIE_CART_ID,goodsId.toString(),CookieUtils.one_day,response);
            }
            return successJson();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return errorJson();
        }
    }

    //购物车数据
    @RequestMapping(value = {"/showCartAjax"}, method = RequestMethod.POST)
    @ResponseBody
    public Map showCartAjax(HttpServletRequest request, HttpServletResponse response) {
        try {
            String cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID,request);
            if(StringUtils.isNotBlank(cart)){
                String[] goodsIds = StringUtils.split(cart, ",");
                Arrays.sort(goodsIds);
                String key = "cart_" + ArrayUtils.toString(goodsIds);
                Map map = (Map) J2CacheUtils.get(Gobals.CACHE_DICTIONARY, key);
                if(map==null || map.size()==0) {
                    map = new HashMap(4);
                    Map params = new HashMap(2);
                    map.put("success", false);
                    params.put("pageSize", goodsIds.length);
                    params.put("ids", cart);
                    MyPager myPager = goodsRestClient.findByLimit(params);
                    if (myPager != null && myPager.getRecords() != null && myPager.getRecords().size() > 0) {
                        List records = myPager.getRecords();
                        map.put("success", true);
                        map.put("records", records);
                        map.put("total", records.size());
                        Map m = null;
                        Double totalPrice = 0d;
                        for (int i = 0; i < records.size(); i++) {
                            m = (Map) records.get(i);
                            if (m.get("price") != null) {
                                Double price = NumberUtils.toDouble(m.get("price").toString());
                                totalPrice += price;
                            }
                            String mainUrl = goodsImgRestClient.getGoodsMainImg(NumberUtils.toLong(m.get("id").toString()));
                            m.put("photo", mainUrl);
                        }
                        map.put("totalPrice", totalPrice);
                        J2CacheUtils.set(Gobals.CACHE_DICTIONARY, key, map);
                    }
                }
                return map;
            }else{
                return errorJson();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return errorJson();
        }
    }

    //购物车数据
    @RequestMapping(value = {"/deleteCartAjax"}, method = RequestMethod.POST)
    @ResponseBody
    public Map deleteCartAjax(Long goodsId,HttpServletRequest request, HttpServletResponse response) {
        Map map = errorJson();
        if(goodsId == null) return map;
        try {
            String cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID,request);
            if(StringUtils.isNotBlank(cart)){
                String[] goodsIds = StringUtils.split(cart,",");
                if(ArrayUtils.contains(goodsIds,goodsId.toString())){
                    goodsIds = (String[]) ArrayUtils.removeElement(goodsIds,goodsId.toString());
                    CookieUtils.addCookie(Gobals.COOKIE_CART_ID,StringUtils.join(goodsIds,","),CookieUtils.one_day,response);
                    map.put("success",true);
                    return map;
                }
            }
        } catch (UnsupportedEncodingException e) {
            return map;
        }
        return map;
    }


}
